package com.wjb.springboot.controller;

import com.wjb.springboot.pojo.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class StudentConsumerController {

    private  final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping(value = "/movie/{id}",method = RequestMethod.GET)
    public Student findById(@PathVariable("id") Long id){
        ServiceInstance instance = discoveryClient.getLocalServiceInstance();
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
       return restTemplate.getForObject("http://user-service/simple/"+id,Student.class);
    }
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public void test(){
        ServiceInstance serviceInstance=loadBalancerClient.choose("user-service");
        System.out.println("---------------第一个服务:"+serviceInstance.getServiceId()+"主机名："+serviceInstance.getHost()+"端口号:"+serviceInstance.getPort());
        ServiceInstance serviceInstance2=loadBalancerClient.choose("user-service2");
        System.out.println("-------第二个服务:"+serviceInstance2.getServiceId()+"主机名："+serviceInstance2.getHost()+"端口号:"+serviceInstance2.getPort());
    }
}
